package org.jsola.hr.web;

import org.apache.commons.lang3.StringUtils;
import org.jsola.core.Page;
import org.jsola.core.Result;
import org.jsola.exception.ParamException;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dto.DepInfoAddDTO;
import org.jsola.hr.dto.DepInfoUpdateDTO;
import org.jsola.hr.entity.CompanyDO;
import org.jsola.hr.query.DepAndInfoQuery;
import org.jsola.hr.query.DepInfoQuery;
import org.jsola.hr.service.IDepInfoService;
import org.jsola.hr.service.IHrPermissionService;
import org.jsola.hr.vo.DepInfoListVO;
import org.jsola.hr.vo.DepInfoVO;
import org.jsola.hr.service.ICompanyService;
import org.jsola.user.core.TokenUser;
import org.jsola.user.core.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;


/**
 * @author zhr
 */
@RestController("hrDepInfoController")
@RequestMapping(HrConstants.API_PATH + "/v1/depInfos")
public class DepInfoController implements IDepInfoControllerAPI {

    @Autowired
    private IDepInfoService depInfoService;

    @Autowired
    private IHrPermissionService hrPermissionService;
    @Autowired
    private ICompanyService companyService;

    @Override
    @PostMapping
    public Result<DepInfoVO> save(@Valid @RequestBody DepInfoAddDTO depInfoAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增部门信息权限校验

        return Result.success(
                depInfoService.save(depInfoAddDTO, tokenUser)
        );
    }


    @Override
    @PutMapping
    public Result<Integer> update(@Valid @RequestBody DepInfoUpdateDTO depInfoUpdateDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改部门信息权限校验

        int count = depInfoService.update(depInfoUpdateDTO, tokenUser);
        if (count == 0) {
            throw new ParamException("更新失败，请刷新页面后重试");
        }
        return Result.success(count);
    }


    @Override
    @DeleteMapping(value = "/{depInfoId}")
    public Result<Integer> delete(@PathVariable String depInfoId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 彻底删除部门信息权限校验

        int count = depInfoService.deleteByIds(tokenUser, depInfoId);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @DeleteMapping
    public Result<Integer> deleteBatch(@RequestBody String[] depInfoIds) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量彻底删除部门信息权限校验

        int count = depInfoService.deleteByIds(tokenUser, depInfoIds);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @GetMapping(value = "/{depInfoId}")
    public Result<DepInfoVO> findById(@PathVariable String depInfoId,
                                      @RequestParam("companyId") String companyId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看部门信息权限校验
        DepInfoVO depInfoVO = depInfoService.selectById(depInfoId, tokenUser.getSiteId());
        if (Objects.nonNull(depInfoVO) && !depInfoVO.getCompanyId().equals(companyId)) {
            return null;
        }
        return Result.success(depInfoVO);
    }

    @Override
    @GetMapping(value = "/listAll")
    public Result<List<DepInfoListVO>> listAll(@Valid DepInfoQuery depInfoQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看部门信息权限校验

        // 扫码入职 查询岗位时用户未登录
        if (tokenUser == null) {
            tokenUser = new TokenUser();
            CompanyDO companyDO = companyService.selectDOByIdNotSite(depInfoQuery.getCompanyId());
            ParamException.notNull(companyDO, "用工单位不存在，请刷新后重试");
            tokenUser.setSiteId(companyDO.getSiteId());
        }

        return Result.success(
                depInfoService.select(depInfoQuery, tokenUser.getSiteId())
        );
    }


    @Override
    @GetMapping
    public Result<Page<DepInfoListVO>> page(@Valid DepInfoQuery depInfoQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                depInfoService.selectPage(depInfoQuery, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/listTree")
    public Result<List<DepInfoListVO>> listTree(@Valid DepInfoQuery depInfoQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看部门信息权限校验

        return Result.success(
                depInfoService.listTree(depInfoQuery, tokenUser.getSiteId())
        );
    }


    @Override
    @GetMapping(value = "/getDepAndEmpInfo/{companyId}")
    public Result<List<DepInfoListVO>> getDepAndEmpInfo(@PathVariable String companyId,
                                                        @Valid DepAndInfoQuery depAndInfoQuery) {
        // todo 查看部门信息权限校验
        return Result.success(
                getDepTree(companyId, depAndInfoQuery)
        );
    }

    /**
     * 部门树查询
     *
     * @param companyId       公司id
     * @param depAndInfoQuery 查询条件
     * @return 部门树
     */
    private List<DepInfoListVO> getDepTree(String companyId, DepAndInfoQuery depAndInfoQuery) {
        TokenUser tokenUser = UserContext.getUser();
        depAndInfoQuery.setCompanyId(companyId);

        // 当前部门没有,默认为公司级
        if (StringUtils.isEmpty(depAndInfoQuery.getCurrentDepId())) {
            // 公司层级部门
            DepInfoVO companyDep = depInfoService.selectByCode(companyId, tokenUser.getSiteId(), companyId);
            if (Objects.isNull(companyDep)) {
                return null;
            } else {
                depAndInfoQuery.setCurrentDepId(companyDep.getId());
            }
        }

        return depInfoService.getDepAndEmpInfo(depAndInfoQuery, tokenUser);
    }

    @Override
    @GetMapping(value = "/selectDepAndEmpInfo/{companyId}")
    public Result<List<DepInfoListVO>> selectDepAndEmpInfo(@PathVariable String companyId,
                                                           @Valid DepAndInfoQuery depAndInfoQuery) {
        return Result.success(
                getDepTree(companyId, depAndInfoQuery)
        );
    }

    @Override
    @GetMapping(value = "/getCompanyDepEmp/{companyId}")
    public Result<DepInfoListVO> getCompanyDepEmp(@PathVariable String companyId,
                                                  @Valid DepAndInfoQuery depAndInfoQuery) {
        TokenUser tokenUser = UserContext.getUser();
        depAndInfoQuery.setCompanyId(companyId);

        // todo 查看部门信息权限校验
        return Result.success(
                depInfoService.getCompanyDepEmp(depAndInfoQuery, tokenUser)
        );
    }

    @Override
    @GetMapping(value = "/selectDepTree")
    public Result<List<DepInfoVO>> selectDepTree(@RequestParam(value = "companyId") String companyId,
                                                 @RequestParam(value = "depName", required = false) String depName) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看部门信息权限校验

        return Result.success(
                depInfoService.selectDepTree(companyId, depName, tokenUser)
        );
    }

    @Override
    @GetMapping(value = "/depManageByDepId")
    public Result<Page<DepInfoVO>> depManageByDepId(DepInfoQuery depInfoQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看部门信息权限校验
        return Result.success(
                depInfoService.depManageByDepId(depInfoQuery, tokenUser)
        );
    }

}

